package cn.jluzh.blog.modules.security.ouath2;

import cn.jluzh.blog.modules.security.eneity.SysUserToken;
import cn.jluzh.blog.modules.security.service.impl.SysUserTokenServiceImpl;
import cn.jluzh.blog.modules.user.entity.SysUser;
import cn.jluzh.blog.modules.user.service.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author hzhii
 */
@Component
public class Oauth2Realm extends AuthorizingRealm {

    @Autowired
    SysUserTokenServiceImpl sysUserTokenService;

    @Autowired
    UserServiceImpl userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权 获取用户的角色和权限
     *@param
     *@return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权操作");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }


    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String accessToken = (String) authenticationToken.getPrincipal();
        //根据accessToken，查询用户信息
        SysUserToken token = sysUserTokenService.getByToken(accessToken);
        if(token == null || token.getExpireDate().getTime() < System.currentTimeMillis()){
            return null;
        }
        SysUser userInfo = userService.getById(token.getUserId());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo, accessToken, getName());

        return info;
    }
}
